// static/script.js
document.addEventListener('DOMContentLoaded', function () {
    fetchWarehouses();
    loadSystemSettings();
});

// 加载系统设置
async function loadSystemSettings() {
    try {
        const response = await fetch('/api/settings/');
        if (!response.ok) {
            throw new Error('获取系统设置失败');
        }

        const settings = await response.json();

        // 更新库房标题
        const warehouseTitle = document.getElementById('warehouse-title');
        if (warehouseTitle && settings.warehouse_title) {
            warehouseTitle.textContent = settings.warehouse_title;
        }

        // 更新物资标题
        const productTitle = document.getElementById('product-title');
        if (productTitle && settings.product_title) {
            productTitle.textContent = settings.product_title;
        }
    } catch (error) {
        console.error('加载系统设置时出错:', error);
    }
}

// 编辑标题函数（库房和物资标题）
function editTitle(titleId, defaultText) {
    const titleElement = document.getElementById(titleId);
    const originalText = titleElement.textContent;

    // 创建输入框
    const input = document.createElement('input');
    input.type = 'text';
    input.value = originalText;
    input.style.fontSize = getComputedStyle(titleElement).fontSize;
    input.style.fontWeight = 'bold';
    input.style.padding = '5px';
    input.style.width = '80%';
    input.style.border = '2px solid #4c9c3d';
    input.style.borderRadius = '4px';

    // 替换标题为输入框
    titleElement.textContent = '';
    titleElement.appendChild(input);
    input.focus();
    input.select();

    // 处理回车键保存
    input.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            saveTitle();
        }
    });

    // 处理失去焦点保存
    input.addEventListener('blur', saveTitle);

    // 保存标题函数
    async function saveTitle() {
        const newText = input.value.trim();
        const settingText = newText || defaultText || originalText;

        // 如果输入为空，则使用默认文本或原始文本
        titleElement.textContent = settingText;

        // 移除输入框
        if (input.parentNode === titleElement) {
            titleElement.removeChild(input);
        }

        // 确定要保存的设置键
        let settingKey = '';
        if (titleId === 'warehouse-title') {
            settingKey = 'warehouse_title';
        } else if (titleId === 'product-title') {
            settingKey = 'product_title';
        }

        // 保存到后端
        if (settingKey) {
            try {
                const response = await fetch('/api/settings/', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        key: settingKey,
                        value: settingText
                    })
                });

                if (!response.ok) {
                    console.error('保存标题设置失败');
                }
            } catch (error) {
                console.error('保存标题设置时出错:', error);
            }
        }
    }
}

async function batchOutStorage(isTrue) {
    const selected = await selectProducts();
    if (selected) {
        await processOutbound(selected,isTrue);
    }
}

async function selectProducts() {
    const selectedProducts = Array.from(document.querySelectorAll('.product-checkbox:checked')).map(checkbox => {
        return {
            id: checkbox.dataset.id,
            row: checkbox.closest('tr')
        };
    });

    if (selectedProducts.length === 0) {
        alert('请先选择要操作的物资');
        return null;
    }

    return selectedProducts;
}

async function DeleteProcessOutbound() {
    // 获取模态框中所有打勾的复选框（注意限定在模态框内）
    const modal = document.getElementById('selected-products-modal');
    const checkedBoxes = modal.querySelectorAll('tbody .product-checkbox:checked');

    if (checkedBoxes.length === 0) {
        alert('请先在列表中勾选要删除的物资');
        return;
    }

    // 记录要删除的ID
    const deletedIds = Array.from(checkedBoxes).map(box => box.value);

    // 从页面删除对应行
    checkedBoxes.forEach(checkbox => {
        const row = checkbox.closest('tr');
        if (row) row.remove();
    });

    // 更新选中物资数据（只过滤掉删除的）
    selectedProductsData = selectedProductsData.filter(
        product => !deletedIds.includes(product.id.toString())
    );

    // 如果全部删完了，显示空列表提示
    if (selectedProductsData.length === 0) {
        document.getElementById('selected-products-list').innerHTML =
            '<p style="text-align: center; padding: 20px;">没有选中的物资</p>';
    }

    alert(`成功删除 ${checkedBoxes.length} 个选中物资`);
}
async function processOutbound(selectedProducts, isTrue) {
    if (!selectedProducts || selectedProducts.length === 0) {
        alert('请先选择要出库的物资');
        return;
    }

    let successCount = 0;
    let errorCount = 0;
    const errors = [];

    // 获取所有选中的复选框
    const checkedCheckboxes = document.querySelectorAll('#selected-products-list .product-checkbox:checked');

    if (checkedCheckboxes.length === 0) {
        alert('请至少勾选一个要出库的物资');
        return;
    }

    // 只处理选中的行
    for (const checkbox of checkedCheckboxes) {
        const row = checkbox.closest('tr');
        const productId = checkbox.value;
        // 找到对应的product对象
        const product = selectedProducts.find(p => p.id == productId);
        if (!product) continue;

        // 将行元素添加到product对象中以便后续使用
        product.row = row;
        console.log('Row content:', product.row.innerHTML);

        const quantity = product.row.querySelector('#product-quantity')?.value;
        const reason = product.row.querySelector('#product-reason')?.value;
        const manager = product.row.querySelector('#product-manager')?.value;
        const prodId = product.row.querySelector('[class*="product-checkbox"]')?.value;
        // Get the product name from the table cell (4th column in the selected products table)
        const productNameCell = product.row.querySelector('td:nth-child(4)');
        const productName = productNameCell?.textContent.trim() || '未知物资';
        // Get current stock quantity (8th column in the selected products table)
        const currentStockCell = product.row.querySelector('td:nth-child(8)');
        const currentStock = parseInt(currentStockCell?.textContent.trim() || '0', 10);
        const quantityNum = parseInt(quantity, 10);

        console.log('Found values:', {quantity: quantityNum, reason, manager, productName, currentStock});

        // Validate required fields
        if (!quantity || !reason || !manager) {
            console.error('Missing required fields for product:', productName);
            errorCount++;
            errors.push(`物资名称：${productName}，原因：缺少必填字段`);
            continue;
        }

        // Validate quantity is a positive number
        if (isNaN(quantityNum) || quantityNum <= 0) {
            console.error('Invalid quantity for product:', productName);
            errorCount++;
            errors.push(`物资名称：${productName}，原因：请输入有效的正数数量`);
            continue;
        }

        // Check stock for outbound operation
        if (isTrue && quantityNum > currentStock) {
            console.error('Insufficient stock for product:', productName);
            errorCount++;
            errors.push(`物资名称：${productName}，原因：库存不足，当前库存 ${currentStock}，出库数量 ${quantityNum}`);
            continue;
        }

        try {
            const response = await fetch('/api/inventory', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    product_id: Number(prodId),
                    quantity: Number(quantity),
                    type: isTrue ? 'out' : 'in',
                    created_at: new Date().toISOString(),
                    remark: reason,
                    user_name: manager
                })
            });

            if (response.ok) {
                const result = await response.json();
                if (result.id) {
                    successCount++;
                } else {
                    errorCount++;
                    errors.push(`物资名称：${productName}，原因：${result.message || '未知错误'}`);
                }
            } else {
                errorCount++;
                const errorData = await response.json().catch(() => ({}));
                errors.push(`物资名称：${productName}，原因：${errorData.message || `请求失败，状态码：${response.status}`}`);
            }
        } catch (error) {
            console.error(`物资ID ${product.id} 出库请求失败:`, error);
            errorCount++;
            errors.push(`物资名称：${productName}，原因：请求异常 - ${error.message}`);
        }
    }

    // 显示汇总信息
    let message = '';
    if (successCount > 0) {
        message += `成功处理 ${successCount} 条物资`;
    }
    if (errorCount > 0) {
        if (message) message += '\n\n';
        message += `处理失败 ${errorCount} 条物资：\n`;
        message += errors.join('\n');
    }

    if (message) {
        alert(message);
    }
}

async function fetchWarehouses(query) {
    console.log("初始化库房列表.")
    const isAll = document.getElementById('isAll');
    isAll.setAttribute('data-id',true)
    const url = query ? `/api/warehouses?name_like=${query}` : '/api/warehouses';
    const response = await fetch(url);
    const warehouses = await response.json();
    const warehouseList = document.getElementById('warehouse-list');
    if (warehouseList) {
        warehouseList.innerHTML = '';
        warehouses.forEach(warehouse => {
            const li = document.createElement('li');

            // 添加复选框
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.className = 'warehouse-checkbox';
            checkbox.dataset.id = warehouse.id;

            // 复选框点击事件
            checkbox.addEventListener('click', (e) => {
                e.stopPropagation(); // 阻止事件冒泡
            });
            li.appendChild(checkbox);

            // 添加可编辑的文本span
            const nameSpan = document.createElement('span');
            nameSpan.textContent = warehouse.name;
            nameSpan.className = 'warehouse-name';
            nameSpan.dataset.id = warehouse.id;

            // 双击编辑功能
            nameSpan.addEventListener('dblclick', function(e) {
                e.stopPropagation(); // 阻止事件冒泡
                const input = document.createElement('input');
                input.type = 'text';
                input.value = this.textContent;
                input.className = 'edit-warehouse-name';

                // 处理回车事件
                input.addEventListener('keypress', async function(e) {
                    if (e.key === 'Enter') {
                        const newName = this.value.trim();
                        if (newName) {
                            try {
                                const response = await fetch('/api/warehouses/', {
                                    method: 'PUT',
                                    headers: {
                                        'Content-Type': 'application/json'
                                    },
                                    body: JSON.stringify({
                                        id: warehouse.id,
                                        name: newName
                                    })
                                });

                                if (response.ok) {
                                    this.replaceWith(nameSpan);
                                    nameSpan.textContent = newName;
                                    fetchWarehouses();
                                } else {
                                    alert('更新失败');
                                }
                            } catch (error) {
                                console.error('更新库房时出错:', error);
                                alert('更新失败');
                            }
                        }
                    }
                });

                // 处理失去焦点事件
                input.addEventListener('blur', async function() {
                    const newName = this.value.trim();
                    if (newName) {
                        try {
                            const response = await fetch('/api/warehouses/', {
                                method: 'PUT',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    id: warehouse.id,
                                    name: newName
                                })
                            });

                            if (response.ok) {
                                this.replaceWith(nameSpan);
                                nameSpan.textContent = newName;
                                fetchWarehouses();
                            } else {
                                alert('更新失败');
                            }
                        } catch (error) {
                            console.error('更新库房时出错:', error);
                            alert('更新失败');
                        }
                    } else {
                        this.replaceWith(nameSpan);
                    }
                });

                this.replaceWith(input);
                input.focus();
            });

            // 点击选择库房（点击span时触发）
            nameSpan.addEventListener('click', (e) => {
                e.stopPropagation(); // 阻止事件冒泡
                // 更新所有库房项的样式
                const allItems = warehouseList.querySelectorAll('li');
                allItems.forEach(item => {
                    item.style.background = "";
                    item.style.color = "";
                    item.style.boxShadow = "";
                });

                // 设置当前选中项的渐变样式
                li.style.background = "linear-gradient(135deg, #67ad5b 0%, #4c9c3d 100%)";
                li.style.color = "white";
                li.style.boxShadow = "0 2px 4px rgba(0,0,0,0.1)";

                // 更新选中库房信息并获取物资
                const selectedWarehouse = document.getElementById('selectedWarehouse');
                selectedWarehouse.textContent = warehouse.name;
                selectedWarehouse.setAttribute('data-id', warehouse.id);
                fetchProducts(warehouse.id);
            });

            li.appendChild(nameSpan);

            // 保留拖拽排序相关属性和事件
            li.dataset.id = warehouse.id;
            li.dataset.index = warehouse.sort;
            li.draggable = true;
            li.addEventListener('dragstart', dragStart);
            li.addEventListener('dragover', dragOver);
            li.addEventListener('drop', drop);
            li.addEventListener('dragend', dragEnd);

            warehouseList.appendChild(li);
        });

        // 默认选中第一个库房
        const firstElement = warehouseList.firstElementChild;
        if (firstElement) {
            const dataId = firstElement.getAttribute('data-id');
            firstElement.style.background = "linear-gradient(135deg, #67ad5b 0%, #4c9c3d 100%)";
            firstElement.style.color = "white";
            firstElement.style.boxShadow = "0 2px 4px rgba(0,0,0,0.1)";
            const selectedWarehouse = document.getElementById('selectedWarehouse');
            selectedWarehouse.textContent = firstElement.querySelector('.warehouse-name').textContent;
            selectedWarehouse.setAttribute('data-id', dataId);
            fetchProducts(dataId);
        }
    }
}

let draggedItem = null;
let draggedItemClone = null;

function dragStart(event) {
    draggedItem = event.target;

    // 创建拖动元素的克隆
    draggedItemClone = draggedItem.cloneNode(true);
    draggedItemClone.style.position = 'absolute';
    draggedItemClone.style.opacity = '0.5';
    draggedItemClone.style.pointerEvents = 'none';
    document.body.appendChild(draggedItemClone);

    // 设置拖动效果
    event.dataTransfer.effectAllowed = "move";

    // 添加拖动时的样式
    draggedItem.classList.add('dragging');

    // 设置拖动图像为透明
    const transparent = document.createElement('div');
    event.dataTransfer.setDragImage(transparent, 0, 0);
}

function dragOver(event) {
    event.preventDefault();
    event.dataTransfer.dropEffect = "move";

    const list = document.getElementById('warehouse-list');
    const items = [...list.querySelectorAll('li:not(.dragging)')];

    // 更新克隆元素的位置
    draggedItemClone.style.left = event.pageX + 'px';
    draggedItemClone.style.top = event.pageY + 'px';

    // 找到最近的可放置位置
    const afterElement = items.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = event.clientY - box.top - box.height / 2;
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;

    // 添加视觉指示器
    items.forEach(item => item.classList.remove('drop-target'));
    if (afterElement) {
        afterElement.classList.add('drop-target');
    }
}

function drop(event) {
    event.preventDefault();

    const list = document.getElementById('warehouse-list');
    const afterElement = [...list.querySelectorAll('li:not(.dragging)')].find(item => {
        const box = item.getBoundingClientRect();
        return event.clientY < box.top + box.height / 2;
    });

    // 移除所有视觉指示器
    list.querySelectorAll('li').forEach(item => {
        item.classList.remove('drop-target');
    });

    if (afterElement) {
        afterElement.before(draggedItem);
    } else {
        list.appendChild(draggedItem);
    }

    // 移除克隆元素
    if (draggedItemClone) {
        draggedItemClone.remove();
        draggedItemClone = null;
    }

    draggedItem.classList.remove('dragging');
    saveNewOrder();
}

function dragEnd() {
    // 移除所有视觉效果
    if (draggedItemClone) {
        draggedItemClone.remove();
        draggedItemClone = null;
    }

    draggedItem.classList.remove('dragging');
    document.querySelectorAll('.drop-target').forEach(item => {
        item.classList.remove('drop-target');
    });

    draggedItem.style.opacity = "1";
    saveNewOrder();
}

// 保存新的排序顺序
function saveNewOrder() {
    const listItems = document.querySelectorAll('#warehouse-list li');
    const newOrder = Array.from(listItems).map((item, index) => ({
        id: parseInt(item.dataset.id),
        sort: index + 1
    }));

    fetch('/api/warehouses/order', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({warehouses: newOrder})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            console.log('库房排序已更新');
            location.reload()
        } else {
            console.error('排序更新失败');
        }
    })
    .catch(error => console.error('请求错误:', error));
}

// 删除选中的库房
async function deleteSelectedWarehouses() {
    const selectedCheckboxes = document.querySelectorAll('.warehouse-checkbox:checked');
    if (selectedCheckboxes.length === 0) {
        alert('请选择要删除的库房');
        return;
    }

    if (confirm(`确定要删除选中的 ${selectedCheckboxes.length} 个库房吗？`)) {
        const deletePromises = Array.from(selectedCheckboxes).map(checkbox => {
            const warehouseId = checkbox.dataset.id;
            return fetch(`/api/warehouses/${warehouseId}`, {
                method: 'DELETE'
            });
        });

        try {
            await Promise.all(deletePromises);
            fetchWarehouses(); // 重新加载库房列表
        } catch (error) {
            console.error('删除库房时出错:', error);
            alert('删除库房时出错');
        }
    }
}

// 显示模态框
function showModal() {
    var modal = document.getElementById("add-warehouse-modal");
    modal.style.display = "block";
}

// 关闭模态框
function closeModal() {
    var modal = document.getElementById("add-warehouse-modal");
    modal.style.display = "none";
}

// 提交添加库房表单
function submitAddWarehouse() {
    var name = document.getElementById("warehouse-name").value;
    var sort = document.getElementById("warehouse-sort").value;
    // 这里应该有验证逻辑
    addWarehouse(name, parseInt(sort)); // 调用添加库房的函数
    closeModal(); // 关闭模态框
    // location.reload();
}

// 为弹窗的关闭按钮添加事件监听
var span = document.getElementsByClassName("close")[0];
if (span) {
    span.onclick = function () {
        closeModal();
    }

}

// 当用户点击模态框外面时关闭模态框
window.onclick = function (event) {
    var modal = document.getElementById("add-warehouse-modal");
    if (event.target == modal) {
        closeModal();
    }
}


// 添加库房
async function addWarehouse(warehouseName, sort) {

    if (warehouseName) {
        let transData = {
            "sort": sort,
            "name": warehouseName,
        }
        fetch('/api/warehouses', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(transData),
        })
            .then(response => response.json())
            .then(data => {
                if (data.id) {
                    addWarehouseToList(data.id, data.name);
                    document.getElementById('warehouse-name').value = ''; // 清空输入框
                } else {
                    alert('添加库房失败');
                }
                location.reload();
            })
            .catch((error) => {
                console.error('Error:', error);
            });


    }
}

// 将新库房添加到列表中
function addWarehouseToList(warehouseId, warehouseName) {
    var warehouseList = document.getElementById('warehouse-list');
    var newWarehouse = document.createElement('li');
    newWarehouse.innerHTML = `
        <span>${warehouseName}</span>
        <button onclick="deleteWarehouse(${warehouseId}, this)">删除</button>
        <button onclick="editWarehouse(${warehouseId}, '${warehouseName}')">编辑</button>
    `;
    warehouseList.appendChild(newWarehouse);
}

// 删除库房
function deleteWarehouse(warehouseId, element) {
    if (confirm("确定要删除这个库房吗？")) {
        fetch(`/api/warehouses/${warehouseId}`, {
            method: 'DELETE',
        })
            .then(response => {
                location.reload();
                if (response.ok) {
                    element.parentNode.remove();
                } else {
                    alert('删除库房失败');
                }
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    }
}

function editWarehouse(warehouseId, warehouseName) {
    // 你可以打开一个编辑模态框，或者直接编辑库房名称
    const editModal = document.getElementById('edit-warehouse-modal');
    const nameField = document.getElementById('edit-warehouse-name');
    nameField.value = warehouseName;
    editModal.style.display = "block";

    const saveButton = document.getElementById('save-warehouse-edit');
    saveButton.onclick = () => saveWarehouseEdit(warehouseId, nameField.value);
}

function closeEditModal() {
    const modal = document.getElementById('edit-warehouse-modal');
    modal.style.display = 'none';
}

function saveWarehouseEdit(warehouseId, newName) {
    fetch(`/api/warehouses/`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({id: warehouseId, name: newName})
    })
        .then(response => response.json())
        .then(data => {
            if (data === "true") {
                // alert('库房更新成功');
                location.reload();  // 重新加载列表，显示更新后的库房名称
            } else {
                alert('更新失败');
            }
        })
        .catch(error => {
            console.error('更新库房时出错:', error);
        });
}


// 打开添加物资弹出框
function openAddProductModal() {
    const modal = document.getElementById('addProductModal');
    if (!modal) {
        console.error('找不到添加物资模态框元素');
        return;
    }

    modal.style.display = 'block';
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.backgroundColor = 'rgba(0,0,0,0.8)';
    modal.style.zIndex = '9999';

    const modalContent = modal.querySelector('.modal-content');
    if (!modalContent) {
        console.error('找不到模态框内容元素');
        return;
    }

    modalContent.style.position = 'fixed';
    modalContent.style.top = '40%';
    modalContent.style.left = '50%';
    modalContent.style.transform = 'translate(-50%, -50%)';
    modalContent.style.backgroundColor = 'white';
    modalContent.style.padding = '20px';
    modalContent.style.borderRadius = '5px';
    modalContent.style.zIndex = '10000';
    modalContent.style.width = '80%';
    modalContent.style.maxWidth = '800px';
    modalContent.style.maxHeight = '80vh';
    modalContent.style.overflowY = 'auto';
    modalContent.style.display = 'flex';
    modalContent.style.flexDirection = 'column';

    // 设置表单容器样式
    const form = modalContent.querySelector('form');
    if (form) {
        form.style.display = 'flex';
        form.style.flexDirection = 'column';
        form.style.gap = '15px';
        form.style.paddingBottom = '20px';
    }

    // 设置表单项样式
    const formGroups = form.querySelectorAll('.form-group');
    formGroups.forEach(group => {
        group.style.display = 'flex';
        group.style.alignItems = 'center';
        group.style.gap = '10px';
    });

    // 设置标签样式
    const labels = form.querySelectorAll('label');
    labels.forEach(label => {
        label.style.minWidth = '120px';
        label.style.textAlign = 'right';
    });

    // 设置输入框样式
    const inputs = form.querySelectorAll('input');
    inputs.forEach(input => {
        input.style.flex = '1';
        input.style.padding = '8px';
        input.style.border = '1px solid #ddd';
        input.style.borderRadius = '4px';
    });

    // 设置图片预览区域样式
    const imagePreview = document.getElementById('image-preview');
    imagePreview.style.display = 'flex';
    imagePreview.style.flexWrap = 'wrap';
    imagePreview.style.gap = '10px';
    imagePreview.style.marginTop = '10px';
    imagePreview.style.maxHeight = '200px';
    imagePreview.style.overflowY = 'auto';
    imagePreview.style.padding = '10px';
    imagePreview.style.backgroundColor = '#f5f5f5';
    imagePreview.style.borderRadius = '4px';

    // 设置按钮样式
    const buttons = form.querySelectorAll('button');
    buttons.forEach(button => {
        button.style.padding = '8px 16px';
        button.style.border = 'none';
        button.style.borderRadius = '4px';
        button.style.cursor = 'pointer';
        button.style.marginTop = '10px';
    });

    // 确保其他内容被遮挡
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.style.filter = 'blur(2px)';
    }
}

// 关闭添加物资弹出框
function closeAddProductModal() {
    const modal = document.getElementById('addProductModal');
    if (!modal) {
        console.error('找不到添加物资模态框元素');
        return;
    }

    modal.style.display = 'none';

    // 恢复其他内容的显示
    const mainContent = document.querySelector('.main-content');
    if (mainContent) {
        mainContent.style.filter = 'none';
    }
}


// 添加物资
async function addProduct(event) {
    event.preventDefault();
    const selectedWarehouse = document.getElementById('selectedWarehouse');
    const dataId = parseInt(selectedWarehouse.getAttribute('data-id'));
    if (!dataId) {
        alert('请先选择库房');
        return;
    }

    const form = document.getElementById('addProductForm');
    const formData = new FormData(form);

    // 添加调试日志
    console.log('表单数据:', {
        name: formData.get('name'),
        model: formData.get('model'),
        spec: formData.get('spec'),
        location: formData.get('location'),
        quantity: formData.get('quantity'),
        in_storage: formData.get('in_storage'),
        out_storage: formData.get('out_storage'),
        user_admin: formData.get('user_admin'),
        remark: formData.get('remark')
    });

    const productData = {
        name: formData.get('name') || '',
        model: formData.get('model') || '',
        spec: formData.get('spec') || '',
        location: formData.get('location') || '',
        quantity: parseInt(formData.get('quantity')) || 0,
        remark: formData.get('remark') || '',
        in_storage: formData.get('in_storage') || "1",
        out_storage: formData.get('out_storage') || '',
        user_admin: formData.get('user_admin') || '',
        warehouse_id: dataId,
        pic: ''
    };

    // 添加调试日志
    console.log('处理后的物资数据:', productData);

    // 处理图片上传
    const imageFile = formData.get('pic');
    if (imageFile && imageFile.size > 0) {
        try {
            const uploadFormData = new FormData();
            uploadFormData.append('file', imageFile);

            const uploadResponse = await fetch('/api/upload', {
                method: 'POST',
                body: uploadFormData
            });

            if (!uploadResponse.ok) {
                throw new Error('图片上传失败');
            }

            const uploadResult = await uploadResponse.json();
            if (!uploadResult.url) {
                throw new Error('未获取到图片URL');
            }

            productData.pic = uploadResult.url;
        } catch (error) {
            console.error('图片上传失败:', error);
            return;
        }
    }

    try {
        // 添加物资
        const productDataCopy = JSON.parse(JSON.stringify(productData));
        console.log('最后的数据：{}', productDataCopy);
        // productDataCopy.in_storage = ''
        // productDataCopy.out_storage = ''
        // productDataCopy.user_admin = ''
        const response = await fetch('/api/products/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(productDataCopy)
        });

        if (!response.ok) {
            throw new Error('添加物资失败');
        }

        const newProduct = await response.json();
        console.log('newprod',newProduct)
        // 如果有入库数量，创建入库记录
        if (productData.in_storage > 0) {
            try {
                const inventoryResponse = await fetch('/api/inventory/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        product_id: newProduct.message.id,
                        quantity: parseInt(productData.in_storage),
                        type: 'in',
                        created_at: new Date().toISOString(),
                        remark: productData.out_storage,
                        user_name: productData.user_admin || '系统'
                    })
                });

                if (!inventoryResponse.ok) {
                    console.error('创建入库记录失败');
                }
            } catch (error) {
                console.error('创建入库记录时出错:', error);
            }
        }

        alert('物资添加成功');
        // 关闭模态框
        const modal = document.getElementById('addProductModal');
        modal.style.display = 'none';
        // 刷新物资列表
        fetchProducts(dataId);
    } catch (error) {
        console.error('添加物资失败:', error);
        alert('添加物资失败: ' + error.message);
    }
}

// 确保表单提交事件只绑定一次
document.addEventListener('DOMContentLoaded', function() {
    const addProductForm = document.getElementById('addProductForm');
    if (addProductForm) {
        // 移除所有已存在的提交事件监听器
        const newForm = addProductForm.cloneNode(true);
        addProductForm.parentNode.replaceChild(newForm, addProductForm);

        // 添加新的事件监听器
        newForm.addEventListener('submit', addProduct);
        console.log('已绑定表单提交事件到 addProductForm');
    } else {
        console.error('找不到 addProductForm 表单元素');
    }
});


// 删除物资
function deleteProduct(element) {
    if (confirm("确定要删除这个物资吗？")) {
        // 这里应该有一个函数来处理删除物资的逻辑，例如发送请求到服务器
        // 示例代码，实际应替换为与后端通信的代码
        element.parentNode.remove();
    }
}

let currentPage = 1;  // 当前页码
let itemsPerPage = 5;  // 每页显示的物资数量，改为let以支持动态修改

// 确保在DOM加载完成后设置分页大小选择事件监听
document.addEventListener('DOMContentLoaded', function() {
    const pageSizeSelect = document.getElementById('pageSizeSelect');
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', function() {
            const selectedValue = this.value;
            itemsPerPage = selectedValue === '0' ? 10000 : parseInt(selectedValue);
            currentPage = 1; // 重置为第一页
            const selectedWarehouse = document.getElementById('selectedWarehouse');
            const warehouseId = selectedWarehouse ? selectedWarehouse.getAttribute('data-id') : null;
            fetchProducts(warehouseId);
        });
    }
});

async function fetchProducts(warehouseId, name, model, specification) {
    const warehouseList = document.getElementById('warehouse-list');
    // warehouseList.innerHTML = '';
    // console.log(warehouseId,name,model,specification)
    const warehouseItems = warehouseList.querySelectorAll('li');
    warehouseItems.forEach(item => {
        item.style.backgroundColor = "";  // 例如蓝色背景
        item.style.color = "";
        const dataId = item.getAttribute('data-id');
        if (dataId && warehouseId) {
            if (warehouseId.toString() === dataId.toString()) {
                let textContent = '';
                item.childNodes.forEach(node => {
                    if (node.nodeType === Node.TEXT_NODE) { // 只获取文本节点
                        textContent += node.textContent.trim();
                        item.style.backgroundColor = "RGB(103, 173, 91)";  // 例如蓝色背景
                        item.style.color = "white";
                    } else {

                    }

                });
                // console.log('text',textContent)
                const selectedWarehouse = document.getElementById('selectedWarehouse');
                selectedWarehouse.textContent = textContent;
                selectedWarehouse.setAttribute('data-id', warehouseId);
            }
        }
    });
    warehouseId = warehouseId || '';
    name = name || '';
    // model = model.toString().replace(/\s+/g, '');
    model = model || '';
    specification = specification || '';
    console.log('model', model)
    const url = `/api/products/?warehouse_id=${warehouseId}&name_like=${name}&model_like=${model}&specification_like=${specification}&page=${currentPage}&page_size=${itemsPerPage}`;
    const response = await fetch(url);
    const data = await response.json();

    const {products, total_count} = data;
    const totalPages = Math.ceil(total_count / itemsPerPage);  // 计算总页数

    // 保存之前选中的物资ID列表
    const selectedIds = selectedProductsData.map(product => product.id);

    displayProducts(data);
    // 设置总条数
    const productList = document.getElementById('product-list');
    if (productList) {
        productList.setAttribute('data-total-count', total_count);
    } else {
        console.error('product-list element not found');
    }
    displayPagination(totalPages);

    // 恢复复选框选中状态
    if (selectedIds.length > 0) {
        document.querySelectorAll('.product-checkbox').forEach(checkbox => {
            if (selectedIds.includes(parseInt(checkbox.value))) {
                checkbox.checked = true;
            }
        });
    }
}

// 保存单个字段的编辑
async function saveProductEdit(productId, field, value) {
    try {
        const response = await fetch('/api/products/', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: productId,
                [field]: value
            })
        });

        if (!response.ok) {
            throw new Error('保存失败');
        }

        // 更新成功后刷新数据
        const selectedWarehouse = document.getElementById('selectedWarehouse');
        const dataId = selectedWarehouse.getAttribute('data-id');
        fetchProducts(dataId);
    } catch (error) {
        console.error('保存编辑时出错:', error);
        alert('保存失败');
    }
}

// 保存物资编辑（用于编辑按钮）
async function saveProductEditWithButton(button, productId) {
    const modal = button.closest('.edit-modal');
    const name = modal.querySelector('#edit-product-name').value;
    const model = modal.querySelector('#edit-product-model').value;
    const spec = modal.querySelector('#edit-product-spec').value;
    const location = modal.querySelector('#edit-product-location').value;
    const quantity = modal.querySelector('#edit-product-quantity').value;
    const in_storage = modal.querySelector('#edit-product-in_storage').value;
    const remark = modal.querySelector('#edit-product-remark').value;
    const out_storage = modal.querySelector('#edit-product-out_storage').value;
    const user_admin = modal.querySelector('#edit-product-user_admin').value;
    const pic = modal.querySelector('#edit-product-pic').value;

    try {
        const response = await fetch(`/api/products/${productId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: productId,
                name: name,
                model: model,
                spec: spec,
                location: location,
                quantity: quantity,
                remark: remark,
                in_storage: in_storage,
                out_storage: out_storage,
                user_admin: user_admin,
                pic: pic
            })
        });

        if (response.ok) {
            alert('物资更新成功');
            fetchProducts(); // 重新加载物资列表
            closeEditModal(modal);
        } else {
            alert('更新失败');
        }
    } catch (error) {
        console.error('更新物资时出错:', error);
        alert('更新失败');
    }
}

function displayProducts(data) {
    const productList = document.getElementById('product-list');
    productList.innerHTML = '';

    if (data.total_count === 0) {
        productList.textContent = '暂无数据';
        return;
    }

    // 存储物资数据以供后续使用
    productList.setAttribute('data-products', JSON.stringify(data.products));

    const table = document.createElement('table');
    table.classList.add('product-table');

    // 创建表头
    const header = document.createElement('thead');
    header.innerHTML = `
        <tr>
            <th><input type="checkbox" id="select-all" onclick="toggleSelectAll(this)"></th>
            <th>序号</th>
            <th>库房名</th>
            <th>名称</th>
            <th>型号</th>
            <th>规格</th>
            <th>位置</th>
            <th>数量</th>
            <th>图片</th>
            <th>备注</th>
            <th>出入库数量</th>
            <th>出入库原因</th>
            <th>管理员</th>
            <th>操作</th>
        </tr>
    `;
    table.appendChild(header);

    // 创建表格内容
    const tbody = document.createElement('tbody');
    data.products.forEach((product, index) => {
        const globalIndex = (currentPage - 1) * itemsPerPage + index + 1;
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><input type="checkbox" class="product-checkbox" value="${product.id}" data-id="${product.id}"></td>
            <td>${globalIndex}</td>
            <td>${product.warehouse_name}</td>
            <td class="editable-cell" data-field="name" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.name || ''}</span></td>
            <td class="editable-cell" data-field="model" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.model || ''}</span></td>
            <td class="editable-cell" data-field="spec" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.spec || ''}</span></td>
            <td class="editable-cell" data-field="location" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.location || ''}</span></td>
            <td class="editable-cell" data-field="quantity" ><span class="display-text">${product.quantity || ''}</span></td>
            <td class="editable-cell" data-field="pic">
                <div class="image-thumbnails" style="width: 50px; height: 50px; cursor: pointer; ${product.pic ? 'border: 1px dashed #ddd;' : ''} display: flex; align-items: center; justify-content: center;" ondblclick="showImageUploadModal(${product.id}, '${product.pic || ''}')">
                    ${product.pic ? `<img style="width: 100%; height: 100%; object-fit: cover;" src="${product.pic}" alt="物资图片" class="thumbnail">` : ''}
                </div>
            </td>
            <td class="editable-cell" data-field="remark" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.remark || ''}</span></td>
            <td class="editable-cell" data-field="in_storage" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.in_storage || ''}</span></td>
            <td class="editable-cell" data-field="out_storage" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.out_storage || ''}</span></td>
            <td class="editable-cell" data-field="user_admin" ondblclick="makeEditable(this, ${product.id})"><span class="display-text">${product.user_admin || ''}</span></td>
            <td>
                <button onclick="inStorage(${product.id},'${product.name}','in')">入库</button>
                <button onclick="inStorage(${product.id},'${product.name}','out')">出库</button>
                <button onclick="viewInventory(${product.id},'${product.name}')">查看</button>
            </td>
        `;
        tbody.appendChild(row);
    });
    table.appendChild(tbody);
    productList.appendChild(table);

    // 为复选框添加事件监听
    document.querySelectorAll('.product-checkbox').forEach((checkbox, index) => {
        checkbox.addEventListener('change', function() {
            const productId = this.value;
            const product = data.products.find(p => p.id == productId);
            if (product) {
                handleCheckboxChange(this, product);
            }
        });
    });
}


/**
 * 加全选/反选功能
 * @param source
 */
function toggleSelectAll(source) {
    const checkboxes = document.querySelectorAll('.product-checkbox');
    const products = JSON.parse(document.getElementById('product-list').getAttribute('data-products') || '[]');

    checkboxes.forEach((checkbox, index) => {
        checkbox.checked = source.checked;
        // 手动触发change事件以更新selectedProductsData
        const event = new Event('change');
        checkbox.dispatchEvent(event);
    });
}


// 存储选中的物资数据
let selectedProductsData = [];

function handleCheckboxChange(checkbox, product) {
    // 确保product是有效物资对象且不是表头行
    if (!product || typeof product.id === 'undefined' || product.id === 'select-all') {
        return;
    }

    if (checkbox.checked) {
        if (!selectedProductsData.some(item => item.id === product.id)) {
            selectedProductsData.push(product);
        }
    } else {
        selectedProductsData = selectedProductsData.filter(item => item.id !== product.id);
    }
    console.log('当前选中的物资:', selectedProductsData);
}


// 显示选中物资的模态框
function getSelectedProducts() {
    const checkboxes = document.querySelectorAll('.product-checkbox:checked');
    return Array.from(checkboxes).map(checkbox => checkbox.value);
}

function toggleAllCheckboxes(source) {
    const checkboxes = document.querySelectorAll('.product-checkbox');
    checkboxes.forEach(checkbox => checkbox.checked = source.checked);
}

function showSelectedProducts() {
    const modal = document.getElementById('selected-products-modal');
    const listContainer = document.getElementById('selected-products-list');

    console.log('当前选中的物资数据:', selectedProductsData);

    if (!selectedProductsData.length) {
        listContainer.innerHTML = '<p style="text-align: center; padding: 20px;">没有选中的物资</p>';
        modal.style.display = 'block';
        return;
    }

    let table = document.createElement('table');
    table.classList.add('product-table');

    let thead = document.createElement('thead');
    thead.innerHTML = `
        <tr>
            <th><input type="checkbox" id="select-all" onclick="toggleAllCheckboxes(this)"></th>
            <th>序号</th>
            <th>库房名</th>
            <th>物资名称</th>
            <th>型号</th>
            <th>规格</th>
            <th>位置</th>
            <th>数量</th>
            <th>备注</th>
            <th>出入库数量</th>
            <th>出入库原因</th>
            <th>管理员</th>
        </tr>
    `;
    table.appendChild(thead);

    let tbody = document.createElement('tbody');
    selectedProductsData.forEach((product, index) => {
        let row = document.createElement('tr');
        row.innerHTML = `
            <td><input type="checkbox" class="product-checkbox" value="${product.id}"></td>
            <td>${index + 1}</td>
            <td>${product.warehouse_name || ''}</td>
            <td>${product.name || ''}</td>
            <td>${product.model || ''}</td>
            <td>${product.spec || ''}</td>
            <td>${product.location || ''}</td>
            <td>${product.quantity || ''}</td>
            <td>${product.remark || ''}</td>
            <td><input type="number" id="product-quantity" class="stock-quantity" min="0"></td>
            <td><input type="text" id="product-reason" class="stock-reason"></td>
            <td><input type="text" id="product-manager" class="stock-manager"></td>
        `;
        tbody.appendChild(row);
    });
    table.appendChild(tbody);

    listContainer.innerHTML = '';
    listContainer.appendChild(table);
    modal.style.display = 'block';
}

function batchInStorage() {
    const selectedProducts = Array.from(document.querySelectorAll('.product-checkbox:checked')).map(checkbox => {
    const row = checkbox.closest('tr');
    return {
        id: checkbox.dataset.id,
        quantity: row.querySelector('.out-quantity')?.value,
        user: row.querySelector('.out-user')?.value
    };
}).filter(product => product.quantity && product.user);
    if (selectedProducts.length === 0) {
        alert('请先选择要入库的物资');
        return;
    }

    const operations = [];
    selectedProducts.forEach(checkbox => {
        console.log(checkbox);
        //<td><input type="number" id="product-quantity" class="stock-quantity" min="0"></td>
        //             <td><input type="text" id="product-reason" class="stock-reason"></td>
        //             <td><input type="text" id="product-manager" class="stock-manager"></td>
        const row = checkbox.closest('tr');
        let quantity = 0;
        if (row.querySelector('.out-quantity')) {
            quantity = row.querySelector('.out-quantity').value;
        }
        let user = ''
        if (row.querySelector('.out-user')) {
            user = row.querySelector('.out-user').value;
        }
        console.log(quantity, user)
        if (quantity && reason && manager) {
            operations.push({
                product_id: Number(checkbox.dataset.id),
                quantity: Number(quantity),
                type: 'in',
                created_at: new Date().toISOString(),
                remark: reason,
                user_name: manager
            });
        }
    });

    if (operations.length === 0) {
        alert('请填写完整的入库信息');
        return;
    }

    fetch('/api/products/in', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({operations})
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('入库成功');
            location.reload();
        } else {
            alert('入库失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('入库请求失败:', error);
        alert('入库请求失败');
    });
}

// 关闭选中物资的模态框
function closeSelectedProductsModal() {
    const modal = document.getElementById('selected-products-modal');
    modal.style.display = 'none';
}

/**
 * 拿到选中的id
 * @returns {*[]}
 */
function getSelectedProducts() {
    let selectedIds = [];
    selectedProductsData.forEach(data=>{
        selectedIds.push(data.id)
    })
    // document.querySelectorAll('.product-checkbox:checked').forEach(checkbox => {
    //     selectedIds.push(checkbox.dataset.id);
    // });
    return selectedIds;
}

/**
 * 调用接口
 */
function exportProducts() {
    // 将所有选中的列表进行展示，需要模态框
    // console.log('123------')
    let selectedIds = getSelectedProducts();
    let warehouseId = getCurrentWarehouseId();
    const selectedWarehouse = document.getElementById('selectedWarehouse');
    const dataId = selectedWarehouse.getAttribute('data-id');
    // console.log('selectIds',selectedIds,'warehouseId',warehouseId,'id',dataId)
    // console.log('----',`/api/products/export-excel?ids=${selectedIds.join(',')}&warehouseId=${dataId}`)
    if (selectedIds.length > 0) {
        window.location.href = `/api/products/export-excel?ids=${selectedIds.join(',')}&warehouseId=${dataId}`;
    } else {
        window.location.href = `/api/products/export-excel?warehouseId=${dataId}`;
    }
}

// 导入物资函数
function importProducts() {
    // 创建隐藏的文件输入框
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.xlsx,.xls'; // 限制文件类型为 Excel
    fileInput.style.display = 'none';

    // 监听文件选择事件
    fileInput.addEventListener('change', async function() {
        if (this.files.length > 0) {
            const formData = new FormData();
            formData.append('file', this.files[0]);

            try {
                const response = await fetch('/api/products/import-excel', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.message) {
                    let alertMessage = '';
                    if (result.count && result.count.length > 0) {
                        alertMessage += '<div class="import-success">导入成功列表:</div><ul class="import-list">';
                        result.count.forEach((item, index) => {
                            alertMessage += `<li>${item.name}</li>`;
                        });
                        alertMessage += '</ul>';
                    }

                    if (result.updated && result.updated.length > 0) {
                        alertMessage += '<div class="import-updated">修改成功列表:</div><ul class="import-list">';
                        result.updated.forEach((item, index) => {
                            alertMessage += `<li>${item.name}</li>`;
                        });
                        alertMessage += '</ul>';
                    }

                    if (result.failed && result.failed.length > 0) {
                        alertMessage += '<div class="import-failed">导入失败列表:</div><ul class="import-list">';
                        result.failed.forEach((item, index) => {
                            alertMessage += `<li>${item.name} ( ${item.remark})</li>`;
                        });
                        alertMessage += '</ul>';
                    }

                    // 创建自定义模态框
                    const modal = document.createElement('div');
                    modal.className = 'custom-alert';
                    modal.innerHTML = `
                        <div class="custom-alert-content">
                            <h3>导入结果</h3>
                            <div class="alert-message">${alertMessage}</div>
                            <button onclick="this.closest('.custom-alert').remove()">确定</button>
                        </div>
                    `;
                    document.body.appendChild(modal);

                    // 刷新物资列表
                    const selectedWarehouse = document.getElementById('selectedWarehouse');
                    const warehouseId = selectedWarehouse.getAttribute('data-id');
                    fetchProducts(warehouseId);
                } else {
                    // 创建错误提示模态框
                    const modal = document.createElement('div');
                    modal.className = 'custom-alert';
                    modal.innerHTML = `
                        <div class="custom-alert-content">
                            <h3>导入失败</h3>
                            <div class="alert-message">${result.error || '未知错误'}</div>
                            <button onclick="this.closest('.custom-alert').remove()">确定</button>
                        </div>
                    `;
                    document.body.appendChild(modal);
                }
            } catch (error) {
                console.error('导入失败:', error);
                alert('导入失败，请检查文件格式是否正确');
            }
        }
    });

    // 触发文件选择
    document.body.appendChild(fileInput);
    fileInput.click();

    // 清理临时创建的输入框
    fileInput.addEventListener('change', function() {
        document.body.removeChild(fileInput);
    });
}


function displayPagination(totalPages) {
    // 更新总条数显示
    const totalCountElement = document.getElementById('totalCount');
    if (totalCountElement) {
        // 从product-list获取总条数
        const productList = document.getElementById('product-list');
        let totalCount = '0';
        if (productList) {
            totalCount = productList.getAttribute('data-total-count') || '0';
        } else {
            console.error('product-list element not found');
        }
        totalCountElement.textContent = totalCount;
    } else {
        console.error('totalCount element not found');
    }

    // 更新当前页码显示
    const currentPageElement = document.getElementById('currentPage');
    if (currentPageElement) {
        currentPageElement.textContent = currentPage;
    }

    // 禁用或启用上一页按钮
    const prevPageButton = document.getElementById('prevPage');
    if (prevPageButton) {
        prevPageButton.disabled = currentPage <= 1;
        prevPageButton.onclick = function() {
            if (currentPage > 1) {
                currentPage--;
                const selectedWarehouse = document.getElementById('selectedWarehouse');
                const warehouseId = selectedWarehouse ? selectedWarehouse.getAttribute('data-id') : null;
                fetchProducts(warehouseId);
            }
        };
    }

    // 禁用或启用下一页按钮
    const nextPageButton = document.getElementById('nextPage');
    if (nextPageButton) {
        nextPageButton.disabled = currentPage >= totalPages;
        nextPageButton.onclick = function() {
            if (currentPage < totalPages) {
                currentPage++;
                const selectedWarehouse = document.getElementById('selectedWarehouse');
                const warehouseId = selectedWarehouse ? selectedWarehouse.getAttribute('data-id') : null;
                fetchProducts(warehouseId);
            }
        };
    }
}

function changePage(page) {
    currentPage = page;
    // const warehouseId = getCurrentWarehouseId();
    const selectedWarehouse = document.getElementById('selectedWarehouse');
    const dataId = parseInt(selectedWarehouse.getAttribute('data-id'));
    const isAll = document.getElementById('isAll');
    const isTrue = isAll.getAttribute('data-id')
    const name = document.getElementById('product-name-search').value;
    const model = document.getElementById('product-model-search').value;
    const specification = document.getElementById('product-specification-search').value;
    console.log('isTrue', isTrue, typeof isTrue)
    if (isTrue === 'true') {
        console.log('1')
        fetchProducts(dataId, name, model, specification);
    } else {
        console.log('2')
        fetchProducts(null, name, model, specification);
    }

}

function searchProducts() {
    // console.log('2')
    const warehouseId = getCurrentWarehouseId();
    const name = document.getElementById('product-name-search').value;
    const model = document.getElementById('product-model-search').value;
    const specification = document.getElementById('product-specification-search').value;
    const selectedWarehouse = document.getElementById('selectedWarehouse');
    const dataId = parseInt(selectedWarehouse.getAttribute('data-id'));
    console.log('warehouseId', dataId, 'name', name, 'model', model, specification, '参数')
    const isAll = document.getElementById('isAll');
    isAll.setAttribute('data-id', true)
    fetchProducts(dataId, name, model, specification);
}

function AllsearchProducts() {
    const name = document.getElementById('product-name-search').value;
    const model = document.getElementById('product-model-search').value;
    const specification = document.getElementById('product-specification-search').value;
    const isAll = document.getElementById('isAll');
    isAll.setAttribute('data-id', false);

    // 构建查询参数
    let queryParams = [];
    if (name) queryParams.push(`name_like=${encodeURIComponent(name)}`);
    if (model) queryParams.push(`model_like=${encodeURIComponent(model)}`);
    if (specification) queryParams.push(`specification_like=${encodeURIComponent(specification)}`);
    queryParams.push(`page=${currentPage}`);
    queryParams.push(`page_size=${itemsPerPage}`);

    // 构建完整的 URL，不包含 warehouse_id
    const url = `/api/products/?${queryParams.join('&')}`;
    console.log('搜索全部物资的URL:', url);

    fetch(url)
        .then(response => response.json())
        .then(data => {
            displayProducts(data);
            displayPagination(Math.ceil(data.total_count / itemsPerPage));
        })
        .catch(error => {
            console.error('搜索全部物资时出错:', error);
            alert('搜索失败，请稍后重试');
        });
}

function exportWarehouses() {
    window.location.href = '/api/warehouses/export';
}


//${product.id},'${product.name}','${product.model}'
//                 ,'${product.spec}','${product.location}','${product.quantity}','${product.remark}'
function updateInventory(productId, name, model, spec, location, quantity, remark) {
    document.getElementById('productModal').style.display = 'block';
    // console.log(productId, name, '12311')
    //将数据回显上去
    const productName = document.getElementById('productName');
    // console.log('prod', productName)
    productName.value = name;

    const id = document.getElementById('selectedWarehouse');
    id.value = productId;

    const productModel = document.getElementById('productModel');
    productModel.value = model;

    const productSpecification = document.getElementById('productSpecification');
    productSpecification.value = spec;

    const locationNumber = document.getElementById('location');
    locationNumber.value = location;

    const productNumber = document.getElementById('productNumber');
    productNumber.value = quantity;

    const remarkNumber = document.getElementById('remark');
    remarkNumber.value = remark;


}

function viewInventory(productId, name) {
    console.log(productId, name, '12311')
    window.location.href = `/inventory/${productId}?name=${name}`;
}
async function inStorage(productId, name, inOrOut) {
    // 获取当前行的入库数量或出库原因
    const row = document.querySelector(`tr:has(input[value="${productId}"])`);
    if (!row) {
        alert('未找到物资行');
        return;
    }

    let quantity = 0;
    let reason = '';
    let userName = '';

    // 获取出入库数量
    const quantityInput = row.querySelector('[data-field="in_storage"] .display-text');
    if (!quantityInput) {
        alert('未找到数量输入框');
        return;
    }
    quantity = parseInt(quantityInput.textContent) || 0;

    // 获取出入库原因
    const remarkInput = row.querySelector('[data-field="out_storage"] .display-text');
    if (remarkInput) {
        reason = remarkInput.textContent || '';
    }

    // 获取管理员字段
    const adminInput = row.querySelector('[data-field="user_admin"] .display-text');
    if (adminInput) {
        userName = adminInput.textContent || '';
    }

    if (quantity <= 0) {
        alert('请输入有效的数量');
        return;
    }

    if (!userName) {
        alert('请输入管理员姓名');
        return;
    }

    // 调用后端接口
    const result = await sendDataToBackend(productId, quantity, inOrOut, reason, new Date(), userName);
    if (result.success) {
        alert(`${inOrOut === 'in' ? '入库' : '出库'}成功！`);

        // 更新物资数量
        const currentQuantityCell = row.querySelector('[data-field="quantity"] .display-text');
        if (currentQuantityCell) {
            const currentQuantity = parseInt(currentQuantityCell.textContent) || 0;
            const newQuantity = inOrOut === 'in' ? currentQuantity + quantity : currentQuantity - quantity;
            currentQuantityCell.textContent = newQuantity;
        }

        // 清空出入库数量
        const inStorageCell = row.querySelector('[data-field="in_storage"] .display-text');
        if (inStorageCell) {
            inStorageCell.textContent = '';
        }

        // 清空出入库原因
        const outStorageCell = row.querySelector('[data-field="out_storage"] .display-text');
        if (outStorageCell) {
            outStorageCell.textContent = '';
        }

        // 清空管理员字段
        const adminCell = row.querySelector('[data-field="user_admin"] .display-text');
        if (adminCell) {
            adminCell.textContent = '';
        }

        // 调用物资修改接口，只清空这三个字段
        try {
            // 先获取物资当前数据
            const productResponse = await fetch(`/api/products/singleProducts/${productId}`);
            if (!productResponse.ok) {
                throw new Error('获取物资信息失败');
            }
            const productData = await productResponse.json();

            // 更新物资信息，只清空这三个字段
            const updateResponse = await fetch('/api/products/', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ...productData,
                    in_storage: '',
                    out_storage: '',
                    user_admin: ''
                })
            });

            if (!updateResponse.ok) {
                throw new Error('清空字段失败');
            }
        } catch (error) {
            console.error('清空字段时出错:', error);
            alert('清空字段失败');
        }

        // 刷新物资列表
        const selectedWarehouse = document.getElementById('selectedWarehouse');
        const dataId = selectedWarehouse.getAttribute('data-id');
        fetchProducts(dataId);
    } else {
        alert(`${inOrOut === 'in' ? '入库' : '出库'}失败：${result.error}`);
    }
}

async function sendDataToBackend(id, quantity, type, remark, created_at, userName) {
    try {
        const response = await fetch(`/api/inventory/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                product_id: id,
                quantity: quantity,
                type: type,
                created_at: created_at,
                remark: remark,
                user_name: userName
            })
        });

        const result = await response.json();
        if (result.error) {
            return { success: false, error: result.error };
        }
        return { success: true };
    } catch (error) {
        console.error('操作失败:', error);
        return { success: false, error: '操作失败' };
    }
}

async function fetchInventoryRecords(productId) {
    const response = await fetch(`/api/inventory?product_id=${productId}`);
    const records = await response.json();
    const inventoryList = document.getElementById('inventory-list');
    inventoryList.innerHTML = '';
    if (records.length === 0) {
        inventoryList.textContent = '暂无数据';
        return;
    }
    records.forEach(record => {
        const div = document.createElement('div');
        div.classList.add('record');
        // 格式化时间
        const date = new Date(record.gmt_create);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        div.innerHTML = `
            <p>数量: ${record.quantity}</p>
            <p>类型: ${record.type}</p>
            <p>时间: ${formattedDate}</p>
        `;
        inventoryList.appendChild(div);
    });
}

function goBack() {
    window.history.back();
}

function deleteWarehouse(warehouseId) {
    if (confirm('确定删除该库房吗？')) {
        fetch(`/api/warehouses/${warehouseId}`, {method: 'DELETE'})
            .then(response => response.json())
            .then(() => {
                // alert('删除成功');
                location.reload();
            });
    }
}

function deleteProduct(productId) {
    if (confirm('确定删除该物资吗？')) {
        fetch(`/api/products/${productId}`, {method: 'DELETE'})
            .then(response => response.json())
            .then(() => {
                alert('删除成功');
                fetchProducts(getCurrentWarehouseId());
            });
    }
}

function deleteInventory(productId) {
    if (confirm('确定删除该入库记录吗？')) {
        fetch(`/api/inventory/${productId}`, {method: 'DELETE'})
            .then(response => response.json())
            .then(() => {
                alert('删除成功');
                // fetchProducts(getCurrentWarehouseId());
            });
        location.reload();
    }
}

function exportInventoryRecords() {
    window.location.href = `/api/inventory/export?product_id=${window.currentProductId}`;
}

function getCurrentWarehouseId() {
    const activeLi = document.querySelector('#warehouse-list li.active');
    return activeLi ? activeLi.dataset.id : '';
}


// let invenCurrentPage = 1;
// const itemsPerPage = 10;
//删除物资不调用接口
async function deleteSelectedProductsNonMethod(){
    const selected = await selectProducts();
    if (selected) {
        await DeleteProcessOutbound(selected);
    }
}
// 删除选中的物资
async function deleteSelectedProducts() {
    const selectedCheckboxes = document.querySelectorAll('.product-checkbox:checked');
    if (selectedCheckboxes.length === 0) {
        alert('请选择要删除的物资');
        return;
    }

    if (confirm(`确定要删除选中的 ${selectedCheckboxes.length} 个物资吗？`)) {
        const deletePromises = Array.from(selectedCheckboxes).map(checkbox => {
            const productId = checkbox.value; // 使用 value 属性获取物资 ID
            if (!productId) {
                console.error('物资ID未找到:', checkbox);
                return Promise.reject(new Error('物资ID未找到'));
            }
            // 从选中物资数据中移除
            selectedProductsData = selectedProductsData.filter(item => item.id != productId);

            return fetch(`/api/products/${productId}`, {
                method: 'DELETE'
            });
        });

        try {
            await Promise.all(deletePromises);
            alert('删除成功！');
            const selectedWarehouse = document.getElementById('selectedWarehouse');
            const dataId = selectedWarehouse.getAttribute('data-id');
            fetchProducts(dataId); // 重新加载物资列表
        } catch (error) {
            console.error('删除物资时出错:', error);
            alert('删除物资时出错');
        }
    }
}

// 编辑选中的物资
async function editSelectedProducts() {
    const selectedCheckboxes = document.querySelectorAll('.product-checkbox:checked');
    if (selectedCheckboxes.length === 0) {
        alert('请选择要编辑的物资');
        return;
    }

    for (const checkbox of selectedCheckboxes) {
        const productId = checkbox.dataset.id;
        await editProduct(productId);
    }
}

// 编辑单个物资
async function editProduct(productId) {
    // 获取物资信息
    const response = await fetch(`/api/products/${productId}`);
    const product = await response.json();

    // 创建编辑框
    const editModal = document.createElement('div');
    editModal.className = 'edit-modal';
    editModal.innerHTML = `
        <div class="modal-content">
            <span class="close" onclick="closeEditModal(this)">&times;</span>
            <h2>编辑物资</h2>
            <label for="edit-product-name">物资名称:</label>
            <input type="text" id="edit-product-name" value="${product.name}">
            <label for="edit-product-model">物资型号:</label>
            <input type="text" id="edit-product-model" value="${product.model}">
            <label for="edit-product-spec">物资规格:</label>
            <input type="text" id="edit-product-spec" value="${product.spec}">
            <label for="edit-product-location">物资位置:</label>
            <input type="text" id="edit-product-location" value="${product.location}">
            <label for="edit-product-quantity">物资数量:</label>
            <input type="number" id="edit-product-quantity" value="${product.quantity}">
            <label for="edit-product-remark">物资备注:</label>
            <input type="text" id="edit-product-remark" value="${product.remark}">
            <label for="edit-product-in_storage">入库数量:</label>
            <input type="text" id="edit-product-in_storage" value="${product.in_storage}">
            <label for="edit-product-out_storage">入库原因:</label>
            <input type="text" id="edit-product-out_storage" value="${product.out_storage}">
            <label for="edit-product-user_admin">管理员:</label>
            <input type="text" id="edit-product-user_admin" value="${product.user_admin}">
            <label for="edit-product-pic">图片:</label>
            <input type="text" id="edit-product-pic" value="${product.pic}">
            <button onclick="saveProductEditWithButton(this, ${productId})">保存</button>
        </div>
    `;
    document.body.appendChild(editModal);
}

// 保存物资编辑
async function saveProductEdit(productId, button) {
    const modal = button.closest('.edit-modal');
    const name = modal.querySelector('#edit-product-name').value;
    const model = modal.querySelector('#edit-product-model').value;
    const spec = modal.querySelector('#edit-product-spec').value;
    const location = modal.querySelector('#edit-product-location').value;
    const quantity = modal.querySelector('#edit-product-quantity').value;
    const in_storage = modal.querySelector('#edit-product-in_storage').value;
    const remark = modal.querySelector('#edit-product-remark').value;
    const out_storage = modal.querySelector('#edit-product-out_storage').value;
    const user_admin = modal.querySelector('#edit-product-user_admin').value;
    const pic = modal.querySelector('#edit-product-pic').value;

    try {
        const response = await fetch(`/api/products/${productId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                id: productId,
                name: name,
                model: model,
                spec: spec,
                location: location,
                quantity: quantity,
                remark: remark,
                in_storage: in_storage,
                out_storage: out_storage,
                user_admin: user_admin,
                pic: pic
            })
        });

        if (response.ok) {
            alert('物资更新成功');
            fetchProducts(); // 重新加载物资列表
            closeEditModal(modal);
        } else {
            alert('更新失败');
        }
    } catch (error) {
        console.error('更新物资时出错:', error);
        alert('更新失败');
    }
}

// 关闭编辑框
function closeEditModal(element) {
    const modal = element.closest('.edit-modal');
    document.body.removeChild(modal);
}

// 切换编辑模式
function toggleEdit(btn, productId) {
    const row = btn.closest('tr');
    const displayTexts = row.querySelectorAll('.display-text');
    const editInputs = row.querySelectorAll('.edit-input');
    const editBtn = row.querySelector('.edit-btn');
    const saveBtn = row.querySelector('.save-btn');
    const cancelBtn = row.querySelector('.cancel-btn');

    displayTexts.forEach(text => text.style.display = 'none');
    editInputs.forEach(input => input.style.display = 'inline-block');
    editBtn.style.display = 'none';
    saveBtn.style.display = 'inline-block';
    cancelBtn.style.display = 'inline-block';
}

// 保存编辑
async function saveEdit(btn, productId) {
    const row = btn.closest('tr');
    const inputs = row.querySelectorAll('.edit-input');
    const productData = {
        id: productId,
        name: inputs[0].value,
        model: inputs[1].value,
        spec: inputs[2].value,
        location: inputs[3].value,
        quantity: parseInt(inputs[4].value),
        remark: inputs[5].value,
        in_storage: parseInt(inputs[6].value),
        out_storage: inputs[7].value,
        user_admin: inputs[8].value,
        pic: inputs[9].value,
    };
    console.log('productdata',productData)
    try {
        const response = await fetch('/api/products/', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(productData)
        });

        // if (response.ok) {
            // 更新成功后刷新数据
            const selectedWarehouse = document.getElementById('selectedWarehouse');
            const dataId = selectedWarehouse.getAttribute('data-id');
            fetchProducts(dataId);
        // } else {
        //     throw new Error('更新失败');
        // }
    } catch (error) {
        console.error('更新物资时出错:', error);
        alert('更新失败');
    }
}

// 取消编辑
function cancelEdit(btn) {
    const row = btn.closest('tr');
    const displayTexts = row.querySelectorAll('.display-text');
    const editInputs = row.querySelectorAll('.edit-input');
    const editBtn = row.querySelector('.edit-btn');
    const saveBtn = row.querySelector('.save-btn');
    const cancelBtn = row.querySelector('.cancel-btn');

    displayTexts.forEach(text => text.style.display = 'inline-block');
    editInputs.forEach(input => input.style.display = 'none');
    editBtn.style.display = 'inline-block';
    saveBtn.style.display = 'none';
    cancelBtn.style.display = 'none';
}

// 处理图片预览
function handleImagePreview(event) {
    const preview = document.getElementById('image-preview');
    preview.innerHTML = '';

    const files = event.target.files;
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.style.width = '100px';
                img.style.height = '100px';
                img.style.objectFit = 'cover';
                img.style.cursor = 'pointer';
                img.onclick = function() {
                    showImageDetail(e.target.result);
                };
                preview.appendChild(img);
            };
            reader.readAsDataURL(file);
        }
    }
}

// 显示图片详情
function showImageDetail(imageUrl) {
    const modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.backgroundColor = 'rgba(0,0,0,0.3)';
    modal.style.backdropFilter = 'blur(12px)';
    modal.style.display = 'flex';
    modal.style.justifyContent = 'center';
    modal.style.alignItems = 'center';
    modal.style.zIndex = '1000';

    const img = document.createElement('img');
    img.src = imageUrl;
    img.style.maxWidth = '98%';
    img.style.maxHeight = '98%';
    img.style.objectFit = 'contain';
    img.style.borderRadius = '12px';
    img.style.boxShadow = '0 8px 32px rgba(0,0,0,0.3)';
    img.style.transition = 'transform 0.3s ease';
    img.style.cursor = 'zoom-in';

    // 添加点击放大/缩小功能
    let isZoomed = false;
    img.onclick = function() {
        if (isZoomed) {
            img.style.transform = 'scale(1)';
            img.style.cursor = 'zoom-in';
        } else {
            img.style.transform = 'scale(1.8)';
            img.style.cursor = 'zoom-out';
        }
        isZoomed = !isZoomed;
    };

    modal.onclick = function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };

    modal.appendChild(img);
    document.body.appendChild(modal);
}

// 修改编辑图片的函数
function editProductImage(productId, currentImage) {
    const modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.backgroundColor = 'rgba(0,0,0,0.8)';
    modal.style.display = 'flex';
    modal.style.flexDirection = 'column';
    modal.style.justifyContent = 'center';
    modal.style.alignItems = 'center';
    modal.style.zIndex = '1000';

    // 创建图片预览
    const img = document.createElement('img');
    img.src = currentImage;
    img.style.maxWidth = '80%';
    img.style.maxHeight = '60%';
    img.style.objectFit = 'contain';
    img.style.marginBottom = '20px';

    // 创建文件上传输入框
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.style.marginBottom = '20px';

    // 创建上传按钮
    const uploadButton = document.createElement('button');
    uploadButton.textContent = '上传新图片';
    uploadButton.style.padding = '10px 20px';
    uploadButton.style.backgroundColor = '#4CAF50';
    uploadButton.style.color = 'white';
    uploadButton.style.border = 'none';
    uploadButton.style.borderRadius = '4px';
    uploadButton.style.cursor = 'pointer';

    // 创建关闭按钮
    const closeButton = document.createElement('button');
    closeButton.textContent = '关闭';
    closeButton.style.padding = '10px 20px';
    closeButton.style.backgroundColor = '#f44336';
    closeButton.style.color = 'white';
    closeButton.style.border = 'none';
    closeButton.style.borderRadius = '4px';
    closeButton.style.cursor = 'pointer';
    closeButton.style.marginTop = '10px';

    // 处理上传按钮点击事件
    uploadButton.onclick = async function() {
        if (fileInput.files.length > 0) {
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                // 上传图片
                const uploadResponse = await fetch('/api/upload', {
                    method: 'POST',
                    body: formData
                });

                if (!uploadResponse.ok) {
                    throw new Error('图片上传失败');
                }

                const uploadResult = await uploadResponse.json();
                console.log('上传结果:', uploadResult);

                if (!uploadResult.url) {
                    throw new Error('未获取到图片URL');
                }

                // 先获取物资当前数据
                const productResponse = await fetch(`/api/products/singleProducts/${productId}`);
                if (!productResponse.ok) {
                    throw new Error('获取物资信息失败');
                }
                const productData = await productResponse.json();

                // 更新物资信息中的图片地址，保留其他字段
                const response = await fetch(`/api/products/`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ...productData,
                        pic: uploadResult.url
                    })
                });

                if (response.ok) {
                    alert('图片更新成功');
                    // 刷新物资列表
                    const selectedWarehouse = document.getElementById('selectedWarehouse');
                    const dataId = selectedWarehouse.getAttribute('data-id');
                    fetchProducts(dataId);
                    document.body.removeChild(modal);
                } else {
                    alert('图片更新失败');
                }
            } catch (error) {
                console.error('更新图片时出错:', error);
                alert('更新图片时出错: ' + error.message);
            }
        } else {
            alert('请选择要上传的图片');
        }
    };

    // 处理关闭按钮点击事件
    closeButton.onclick = function() {
        document.body.removeChild(modal);
    };

    // 添加所有元素到模态框
    modal.appendChild(img);
    modal.appendChild(fileInput);
    modal.appendChild(uploadButton);
    modal.appendChild(closeButton);

    // 点击模态框背景关闭
    modal.onclick = function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };

    document.body.appendChild(modal);
}

// 处理图片上传
async function handleImageUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await fetch('/api/upload', {
            method: 'POST',
            body: formData
        });

        if (!response.ok) {
            throw new Error('图片上传失败');
        }

        const result = await response.json();
        if (!result.url) {
            throw new Error('未获取到图片URL');
        }

        // 更新图片预览
        const preview = document.getElementById('imagePreview');
        preview.src = result.url;
        preview.style.display = 'block';

        // 显示清除按钮
        const clearButton = document.getElementById('clearImageButton');
        clearButton.style.display = 'block';

        // 保存图片URL到隐藏输入框
        document.getElementById('productImageUrl').value = result.url;
    } catch (error) {
        console.error('图片上传失败:', error);
        alert('图片上传失败: ' + error.message);
    }
}

// 清除图片
function clearImage() {
    const preview = document.getElementById('imagePreview');
    preview.src = '';
    preview.style.display = 'none';

    // 隐藏清除按钮
    const clearButton = document.getElementById('clearImageButton');
    clearButton.style.display = 'none';

    // 清空图片URL
    document.getElementById('productImageUrl').value = '';
}

// 显示图片上传模态框
function showImageUploadModal(productId, currentImage = '') {
    const modal = document.getElementById('imageUploadModal');
    if (!modal) {
        createImageUploadModal();
    }
    modal.style.display = 'block';
    document.getElementById('productId').value = productId;

    // 获取预览图片元素和清除按钮
    const preview = document.getElementById('imagePreview');
    const clearButton = document.getElementById('clearImageButton');

    // 如果有当前图片，显示它
    if (currentImage) {
        preview.src = currentImage;
        preview.style.display = 'block';
        clearButton.style.display = 'block';
        document.getElementById('productImageUrl').value = currentImage;
    } else {
        preview.src = '';
        preview.style.display = 'none';
        clearButton.style.display = 'none';
        document.getElementById('productImageUrl').value = '';
    }
}

// 更新物资图片
async function updateProductImage() {
    const productId = document.getElementById('productId').value;
    const imageUrl = document.getElementById('productImageUrl').value;

    try {
        // 先获取物资当前数据
        const productResponse = await fetch(`/api/products/singleProducts/${productId}`);
        if (!productResponse.ok) {
            throw new Error('获取物资信息失败');
        }
        const productData = await productResponse.json();

        // 更新物资信息中的图片地址，保留其他字段
        const response = await fetch(`/api/products/`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                ...productData,
                pic: imageUrl
            })
        });

        if (!response.ok) {
            throw new Error('更新图片失败');
        }

        // 更新本地物资列表中的图片
        const product = products.find(p => p.id === parseInt(productId));
        if (product) {
            product.pic = imageUrl;
            renderProducts(products);
        }

        // 关闭模态框
        const modal = document.getElementById('imageUploadModal');
        modal.style.display = 'none';
        const selectedWarehouse = document.getElementById('selectedWarehouse');
        const dataId = selectedWarehouse.getAttribute('data-id');
        fetchProducts(dataId);
    } catch (error) {
        const modal = document.getElementById('imageUploadModal');
        modal.style.display = 'none';
        console.error('更新图片失败:', error);
        const selectedWarehouse = document.getElementById('selectedWarehouse');
        const dataId = selectedWarehouse.getAttribute('data-id');
        fetchProducts(dataId);
    }
}

function createImageUploadModal() {
    const modal = document.createElement('div');
    modal.id = 'imageUploadModal';
    modal.className = 'modal';
    modal.style.backgroundColor = 'rgba(0,0,0,0.3)';
    modal.style.backdropFilter = 'blur(12px)';
    modal.innerHTML = `
        <div class="modal-content" style="
            background: rgba(255, 255, 255, 0.9);
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.2);
            max-width: 800px;
            width: 95%;
            margin: 20px auto;
            position: relative;
            backdrop-filter: blur(8px);
            max-height: 90vh;
            overflow-y: auto;
        ">
            <span class="close" style="
                position: absolute;
                right: 20px;
                top: 20px;
                font-size: 28px;
                cursor: pointer;
                color: #666;
                transition: color 0.3s;
                z-index: 1001;
            ">&times;</span>
            <h2 style="
                margin: 0 0 25px 0;
                color: #333;
                text-align: center;
                font-size: 24px;
            ">上传物资图片</h2>
            <div class="image-upload-container" style="
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 25px;
            ">
                <div class="image-preview-container" style="
                    width: 500px;
                    height: 500px;
                    border: 2px dashed #ddd;
                    border-radius: 12px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    overflow: hidden;
                    background: rgba(249, 249, 249, 0.8);
                    transition: border-color 0.3s;
                    position: relative;
                ">
                    <img id="imagePreview" style="
                        max-width: 100%;
                        max-height: 100%;
                        object-fit: contain;
                        display: none;
                        border-radius: 8px;
                        transition: transform 0.3s ease;
                        cursor: zoom-in;
                    ">
                    <div class="zoom-controls" style="
                        position: absolute;
                        bottom: 10px;
                        right: 10px;
                        display: flex;
                        gap: 5px;
                        background: rgba(0,0,0,0.5);
                        padding: 5px;
                        border-radius: 5px;
                        z-index: 1002;
                    ">
                        <button class="zoom-in" style="
                            background: rgba(255,255,255,0.9);
                            border: none;
                            border-radius: 3px;
                            padding: 5px 10px;
                            cursor: pointer;
                            font-size: 16px;
                            font-weight: bold;
                            min-width: 30px;
                            transition: background-color 0.3s;
                        ">+</button>
                        <button class="zoom-out" style="
                            background: rgba(255,255,255,0.9);
                            border: none;
                            border-radius: 3px;
                            padding: 5px 10px;
                            cursor: pointer;
                            font-size: 16px;
                            font-weight: bold;
                            min-width: 30px;
                            transition: background-color 0.3s;
                        ">-</button>
                        <button class="zoom-reset" style="
                            background: rgba(255,255,255,0.9);
                            border: none;
                            border-radius: 3px;
                            padding: 5px 10px;
                            cursor: pointer;
                            font-size: 14px;
                            transition: background-color 0.3s;
                        ">重置</button>
                    </div>
                </div>
                <div style="
                    display: flex;
                    gap: 15px;
                    width: 100%;
                    justify-content: center;
                    margin-top: 20px;
                ">
                    <label for="imageUpload" style="
                        padding: 12px 24px;
                        background: rgba(76, 175, 80, 0.9);
                        color: white;
                        border-radius: 6px;
                        cursor: pointer;
                        display: inline-block;
                        font-size: 16px;
                        transition: background-color 0.3s;
                    ">选择图片</label>
                    <input type="file" id="imageUpload" accept="image/*" onchange="handleImageUpload(event)" style="display: none;">
                    <button id="clearImageButton" onclick="clearImage()" style="
                        padding: 12px 24px;
                        background: rgba(244, 67, 54, 0.9);
                        color: white;
                        border: none;
                        border-radius: 6px;
                        cursor: pointer;
                        display: none;
                        font-size: 16px;
                        transition: background-color 0.3s;
                    ">清除图片</button>
                </div>
                <input type="hidden" id="productImageUrl">
                <input type="hidden" id="productId">
                <button onclick="updateProductImage()" style="
                    padding: 12px 30px;
                    background: rgba(33, 150, 243, 0.9);
                    color: white;
                    border: none;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 18px;
                    margin-top: 15px;
                    transition: background-color 0.3s;
                ">保存</button>
            </div>
        </div>
    `;

    // 添加悬停效果
    const style = document.createElement('style');
    style.textContent = `
        #imageUploadModal .modal-content label:hover { background-color: rgba(69, 160, 73, 0.9); }
        #imageUploadModal .modal-content #clearImageButton:hover { background-color: rgba(218, 25, 11, 0.9); }
        #imageUploadModal .modal-content button[onclick="updateProductImage()"]:hover { background-color: rgba(25, 118, 210, 0.9); }
        #imageUploadModal .close:hover { color: #333; }
        #imageUploadModal .image-preview-container:hover { border-color: #2196F3; }
        #imagePreview:hover { transform: scale(1.05); }
        .zoom-controls button:hover { 
            background-color: rgba(255,255,255,1) !important;
            transform: scale(1.1);
        }
    `;
    document.head.appendChild(style);

    // 添加图片缩放功能
    const preview = modal.querySelector('#imagePreview');
    const zoomControls = modal.querySelector('.zoom-controls');
    let currentScale = 1;
    const scaleStep = 0.1;
    const maxScale = 3;
    const minScale = 0.5;

    // 缩放功能
    function updateZoom(scale) {
        currentScale = Math.min(Math.max(scale, minScale), maxScale);
        preview.style.transform = `scale(${currentScale})`;
    }

    modal.querySelector('.zoom-in').onclick = () => updateZoom(currentScale + scaleStep);
    modal.querySelector('.zoom-out').onclick = () => updateZoom(currentScale - scaleStep);
    modal.querySelector('.zoom-reset').onclick = () => updateZoom(1);

    // 鼠标滚轮缩放
    preview.addEventListener('wheel', (e) => {
        e.preventDefault();
        if (e.ctrlKey) {
            const delta = e.deltaY > 0 ? -scaleStep : scaleStep;
            updateZoom(currentScale + delta);
        }
    });

    // 关闭按钮事件
    modal.querySelector('.close').onclick = function() {
        modal.style.display = 'none';
    };

    // 点击模态框外部关闭
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = 'none';
        }
    };

    document.body.appendChild(modal);
}

// 添加双击编辑功能
function makeEditable(cell, productId) {
    const displayText = cell.querySelector('.display-text');
    const currentValue = displayText.textContent;
    const field = cell.getAttribute('data-field');

    // 创建输入框
    const input = document.createElement('input');
    input.type = 'text';
    input.value = currentValue;
    input.style.width = '100%';
    input.style.padding = '4px';
    input.style.boxSizing = 'border-box';

    // 替换显示文本为输入框
    displayText.style.display = 'none';
    cell.appendChild(input);
    input.focus();

    // 处理输入框失去焦点事件
    input.addEventListener('blur', async function() {
        const newValue = this.value;
        displayText.textContent = newValue;
        displayText.style.display = '';
        cell.removeChild(this);

        // 更新后端数据
        try {
            // 从表格中获取所有字段的值
            const row = cell.parentElement;
            const quantitysInt = row.querySelector('[data-field="quantity"] .display-text').textContent;
            let count = parseInt(quantitysInt)
            const updatedData = {
                id: productId,
                name: row.querySelector('[data-field="name"] .display-text').textContent,
                model: row.querySelector('[data-field="model"] .display-text').textContent,
                spec: row.querySelector('[data-field="spec"] .display-text').textContent,
                location: row.querySelector('[data-field="location"] .display-text').textContent,
                quantity: row.querySelector('[data-field="quantity"] .display-text').textContent,
                remark: row.querySelector('[data-field="remark"] .display-text').textContent,
                in_storage: row.querySelector('[data-field="in_storage"] .display-text').textContent,
                out_storage: row.querySelector('[data-field="out_storage"] .display-text').textContent,
                user_admin: row.querySelector('[data-field="user_admin"] .display-text').textContent,
                pic: row.querySelector('[data-field="pic"] img')?.src || ''
            };

            // 更新当前修改的字段
            updatedData[field] = newValue;
            updatedData.quantity = count
            console.log('updateData',updatedData,count)
            const response = await fetch(`/api/products`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updatedData)
            });

            // if (!response.ok) {
            //     throw new Error('更新失败');
            // }

            // 重新加载物资列表
            const selectedWarehouse = document.getElementById('selectedWarehouse');
            const dataId = selectedWarehouse.getAttribute('data-id');
            fetchProducts(dataId);
        } catch (error) {
            console.error('更新失败:', error);
            // alert('更新失败，请重试');
        }
    });

    // 处理回车键事件
    input.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            this.blur();
        }
    });
}
